import { useState } from 'react';
import CodeDiff from "react-code-diff-lite";
import codeGenerator from './woker';
import { Button, Drawer } from '@alifd/next';
import './index.scss';
export default () => {
  const [showDiffContainer, setShowDiffContainer] = useState(false);
  const [newJS, setNewJS] = useState('');
  const [oldJS, setOldJS] = useState('');
  const [newCSS, setNewCSS] = useState('');
  const [oldCSS, setOldCSS] = useState('');
  const generalCode = async () => {
    const lastCode = await getLastSaveCode();
    if(!lastCode) return;
    setNewJS(lastCode.jsCode);
    setOldJS(lastCode.jsCode);
    setNewCSS(lastCode.cssCode);
    setOldCSS(lastCode.cssCode);
    setShowDiffContainer(true);
  };
  const closeDiffDrawer = async () => {
    setShowDiffContainer(false);
  }
  const deployCode = async () => {
    console.log('--- 发布代码');
  };
  return (<>
    <Button type="primary" onClick={() => generalCode()}>导出代码</Button>
    <Drawer width={'80%'} className="code-diff-container" title="Code Diff" placement="right" visible={showDiffContainer} onClose={() => closeDiffDrawer()}>
      <div className='diff-wrap'>
        <div className="diff-view">
          <div className="diff-v2">
            <p className="diff-file">index.js [旧 | 新]</p>
            <CodeDiff oldStr={oldJS} newStr={`123\n456`} context={9999} outputFormat="side-by-side" />
            <p className="diff-file">index.scss [旧 | 新]</p>
            <CodeDiff oldStr={oldCSS} newStr={`123\n456`} context={9999} outputFormat="side-by-side" />
          </div>
        </div>
        <div>
          <Button type="primary" onClick={() => deployCode()}>提交发布</Button>
        </div>
      </div>
    </Drawer>
  </>
  );
}

async function getLastSaveCode() {
  // 从 ls 中获取协议，协议来自于 保存搭建代码
  let originSchema: any = window.localStorage.getItem('general:projectSchema');
  if(!originSchema){ alert('需要保存'); return null; }
  originSchema = JSON.parse(originSchema);
  // 这里掉异常依赖的组件
  originSchema.componentsMap = originSchema.componentsMap.filter((c: any) => c.package);
  const genCodeResult = await codeGenerator(originSchema) as any;
  console.log('↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓');
  console.log('输出结果：', originSchema, genCodeResult );
  // 拿出JS,CSS文件代码
  const outFiles = genCodeResult.buildResult[0]['files'];
  const outCode = {
    jsCode: outFiles[0].content,
    cssCode: outFiles[1].content
  };
  return outCode;
}
